using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.Checkup;
using B.S.NewMedical.Api.Read.DTOS.Checkup;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.Checkup
{
    /// <summary>
    /// 获取所有检查项目分类处理程序
    /// </summary>
    public class GetAllCheckupCategoriesHandler : IRequestHandler<GetAllCheckupCategoriesCommand, ApiResult<List<CheckupCategoryDto>>>
    {
        private readonly IBaseRepository<CheckupCategoryModel> _checkupCategoryRepository;
        private readonly ILogger<GetAllCheckupCategoriesHandler> _logger;
        private readonly IMapper _mapper;

        public GetAllCheckupCategoriesHandler(
            IBaseRepository<CheckupCategoryModel> checkupCategoryRepository,
            ILogger<GetAllCheckupCategoriesHandler> logger,
            IMapper mapper)
        {
            _checkupCategoryRepository = checkupCategoryRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<CheckupCategoryDto>>> Handle(GetAllCheckupCategoriesCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取所有检查项目分类");

                // 查询所有未删除的检查项目分类
                var checkupCategories = await _checkupCategoryRepository.GetAll()
                    .Where(cc => !cc.IsDeleted)
                    .OrderBy(cc => cc.Id)
                    .ToListAsync(cancellationToken);

                // 转换为DTO
                var checkupCategoryDtos = _mapper.Map<List<CheckupCategoryDto>>(checkupCategories);

                return new ApiResult<List<CheckupCategoryDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取检查项目分类成功",
                    Data = checkupCategoryDtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取检查项目分类时发生异常");
                return new ApiResult<List<CheckupCategoryDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取检查项目分类失败：" + ex.Message,
                    Data = new List<CheckupCategoryDto>()
                };
            }
        }
    }
} 